
#ifndef  NDEBUG
#define NDEBUG
#endif 

#include <utility.h>
#include <version.h>
#include "bsp.h"
#include "simple_protocol.h"
#include "debug.h"

void fun_delay_reset(uint32_t time);

static int sys_reset(buffer_t* command, buffer_t* response){
	fun_delay_reset(1000);
	return ERR_NONE;
}

static int sys_start_bootloader(buffer_t* command, buffer_t* response){
	fun_delay_reset(500);
	return ERR_NONE;
}

static int sys_get_sys_ticks(buffer_t* command, buffer_t* response){
	uint32_t ticks = 0;
	net_buf_simple_add_mem(response, (const uint8_t *)&ticks, sizeof(ticks));
	return ERR_NONE;
}

static int sys_get_version_string(buffer_t* command, buffer_t* response){
	uint8_t len = GetVersionSw2((char *) response->data);
	if(len > command->data[0]){
		len = command->data[0];
	}
	LOG_D("len %d, ver:%s", len, response->data);
	net_buf_simple_push_u8(response, len);
	net_buf_simple_add(response, len);
	return ERR_NONE;
}

static int sys_get_usb_type(buffer_t* command, buffer_t* response){
	net_buf_simple_add_u8(response, 1);
	return ERR_NONE;
}

static int sys_get_device_type(buffer_t* command, buffer_t* response){
	net_buf_simple_add_u8(response, 11);
	return ERR_NONE;
}


static int sys_sleep(buffer_t* command, buffer_t* response){
	net_buf_simple_add_u8(response, 0);
	return ERR_NONE;
}

static int sys_get_device_id(buffer_t* command, buffer_t* response){
	uint32_t id[3];
	BSP_GetUid(id);
	net_buf_simple_add_mem(response, (uint8_t*)id, sizeof(id));
	return ERR_NONE;
}

static int sys_set_paramters(buffer_t* command, buffer_t* response){
	memcpy(simpleConfig.params, command->data + 1, UTIL_MIN(command->data[0], sizeof(simpleConfig.params)));
	net_buf_simple_add_u8(response, 1);
	return ERR_NONE;
}

static int sys_get_last_error(buffer_t* command, buffer_t* response){
	net_buf_simple_add_mem(response, (uint8_t*)&simpleConfig.lastError, sizeof(simpleConfig.lastError));
	return ERR_NONE;
}


static int sys_get_sn(buffer_t* command, buffer_t* response){
	uint8_t len = strlen(SIMPLE_PROTOCOL_SERNO);
	len = UTIL_MIN(command->data[0] , len);
	net_buf_simple_add_u8(response, len);
	net_buf_simple_add_mem(response, SIMPLE_PROTOCOL_SERNO, len);
	return ERR_NONE;
}

static int sys_set_protocolformat(buffer_t* command, buffer_t* response){
	extern simple_protocol_context_t protocol_context;
	protocol_context.flag = command->data[0];
	return ERR_NONE;
}

static const api_entry_t api_sys_list[] = {
	[0] = sys_set_protocolformat,
	[1] = sys_reset,
	[2] = sys_start_bootloader,
	[3] = sys_get_sys_ticks,
	[4] = sys_get_version_string,
	[5] = sys_get_usb_type,
	[6] = sys_get_device_type,
	[7] = sys_sleep,
	[8] = sys_get_device_id,
	[9] = sys_set_paramters,
	[10] = sys_get_last_error,
	[13] = sys_get_sn,
};

static int sys_api(buffer_t* command, buffer_t* response){
	const uint8_t num = sizeof(api_sys_list)/sizeof(api_sys_list[0]);
	return protocol_call_api(api_sys_list, num, command, response);
}


SIMPLE_API_DEFINE(API_CLASS_SYS, sys_api);



